package net.andvari.android.mobilesignalcondition;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;


/**
 * {@code Service} for monitoring the {@code REGISTERED_RECEIVER_ONLY} {@code Intent}s {@link Intent#ACTION_SCREEN_ON} and
 * {@link Intent#ACTION_SCREEN_OFF}.
 */
public final class BackgroundService extends Service
{

	/**
	 * REPRESENTATION INVARIANTS:
	 * <ol>
	 * <li>The {@link #REQUEST_REQUERY} {@code Intent} should not be modified after its static initialization completes</li>
	 * <li>{@link #isRunning} returns true only while the service is running</li>
	 * <li>{@link #mReceiver} is registered only while the service is running</li>
	 * <li>{@link #displayState} must be one of: -1 for unknown, 0 for off, or 1 for on</li>
	 * </ol>
	 */

	/**
	 * {@code Intent} to ask <i>Locale</i> to re-query our conditions. Cached here so that we only have to create this object
	 * once.
	 */
	private static final Intent REQUEST_REQUERY = new Intent(com.twofortyfouram.Intent.ACTION_REQUEST_QUERY);

	static
	{
		/*
		 * The Activity name must be present as an extra in this Intent, so that Locale will know who needs updating. This intent
		 * will be ignored unless the extra is present.
		 */
		REQUEST_REQUERY.putExtra(com.twofortyfouram.Intent.EXTRA_ACTIVITY, EditActivity.class.getName());
	}

	/**
	 * Indicates whether the {@code Service} is running or not. Since a {@code Service} is a singleton object by definition in
	 * Android, we can make this a static global.
	 */
	private static boolean isRunning = false;

	/**
	 * A {@code BroadcastReceiver} to monitor {@link Intent#ACTION_SCREEN_ON} and {@link Intent#ACTION_SCREEN_OFF}.
	 */
	private static TelephonyManager tlm;
	private static SignalListener sl = new SignalListener();

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void onCreate()
	{
		super.onCreate();

		tlm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		
		sl.setContext(this);
		
		Log.d("GSMSignalCondition", "Starting Phone state Listener");
		
		tlm.listen(sl,PhoneStateListener.LISTEN_SERVICE_STATE);
		
		isRunning = true;
		
	}

	/**
	 * Determines whether the service is actually running or not.
	 *
	 * @return true if the service is running. False if it is not.
	 */
	public static boolean isRunning()
	{
		return isRunning;
	}


	public static int getGSMState(final Context c)
	{
		int state = -1;
		state = sl.getState();
		return state;
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public IBinder onBind(final Intent arg0)
	{
		return null;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void onDestroy()
	{
		super.onDestroy();
		isRunning = false;
	}

}